package com.itany.springcloud.springcloudsso.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/*
    jwt
    json nweb token
    优势
        jwt数据量小传输快
        维护成本小
        加密数据安全
        校验

    jwt结构
        header      头
        payload     载荷
        signature   签名

        头{
            alg：签名算法
            type：令牌类型
        }

        载荷{
            任意数据
            username:abc
            password:123
            官方建议的key
            iss(issuer)：签发人
            exp(expiration time)：过期时间
            sub(subject)：主题
            aud(audience)：受众
            nbf(Not Before)：生效时间
            iat(Issued At)：签发时间
            jti(JWT ID)：编号
        }

        签名{
            签名以上两部分的信息进过哈希算法进行加密后生成的数据
            校验
        }


 */
public class JWTUtil {

    public static String SECRET="abc";
    public static Integer JWT_TIME=600;

    public static String getJWT(Map<String,String> payload){

        Calendar calendar=Calendar.getInstance();
        calendar.add(Calendar.SECOND,JWT_TIME);

        JWTCreator.Builder builder= JWT.create();

        payload.forEach((k,v)->builder.withClaim(k,v));

        return builder.withExpiresAt(calendar.getTime())
                      .sign(Algorithm.HMAC256(SECRET));
    }


    public static DecodedJWT decodedJWT(String jwt){
        JWTVerifier jwtVerifier=JWT.require(Algorithm.HMAC256(SECRET)).build();
        return jwtVerifier.verify(jwt);
    }

    public static String getPayload(String key,String jwt){
        DecodedJWT decodedJWT=decodedJWT(jwt);
        return decodedJWT.getClaim(key).asString();
    }


    public static void main(String[] args) {

        Map<String,String> payload=new HashMap<>();
        payload.put("username","abc");
        payload.put("password","123");

        String jwt=getJWT(payload);

        System.out.println("jwt = " + jwt);

        // try {
        //     Thread.sleep(6000);
        // } catch (InterruptedException e) {
        //     e.printStackTrace();
        // }

        // DecodedJWT decodedJWT=decodedJWT(jwt);
        // String username=decodedJWT.getClaim("username").asString();
        // String password=decodedJWT.getClaim("password").asString();

        String username=getPayload("username",jwt);
        String password=getPayload("password",jwt);

        System.out.println("username = " + username);
        System.out.println("password = " + password);


    }

}
